import axios from 'axios';
import { FetchLogin, FetchUserInfo } from '@/services'
import { AsyncComponentRoutes } from '@/router/config'

// 封装一个递归过滤函数，用来过滤路由函数
const filterRoutes = (routes: any, userId: number) => {
  // 1. 过滤 第一层
  let filterArr = routes.filter((v:any) => v.meta.userId.indexOf(userId) !== -1)
  routes.forEach((item: any) => {
    item.children = item.children && item.children.length && filterRoutes(item.children, userId)
  })
  // 2. 递归 过滤children
  return filterArr;
}

const users = {
  state: {
    token: '', // 登陆token
    asyncRoutes: [], // 放置用户过滤后的路由
    roles: [], // 放置用户角色信息
    userInfo: {}, // 用户信息
  },
  mutations: {
    // 登陆toKen
    SET_TOEKN(state:any, data:any) {
      state.token = data;
    },
    // 过滤路由
    SET_ASYNC_ROUTES(state:any, data:any) {
      console.log('useId: ', data)
      const filterArr = filterRoutes(AsyncComponentRoutes, data[0])
      console.log('filterArr：---》', filterArr)
      state.asyncRoutes = filterArr;
    },
    // 用户信息
    SET_USER_INFO(state:any, data:any) {
      state.userInfo = data;
    },
    // 给用户身份数组添加值，用来判断时候已经添加过路由了
    SET_ROLES(state:any, data:any) {
      state.roles.push(data[0]);
    }
  },
  actions: {
    // 登陆接口
    GetLogin({ commit }:any, { userName, pwd }: any) {
      return new Promise((resolve, reject) => {
        FetchLogin({userName, pwd})
        .then(result => {
          const token = result.data.data.token;
          commit('SET_TOEKN', token)
          resolve({ msg: '登陆成功', code: 0 })
        })
      })
    },
    // 获取用户信息。（一定是用户登陆之后，才能调用）
    GetUserInfo({commit, state}: any) {
      return new Promise((resolve, reject) => {
        FetchUserInfo({token: state.token}).then(result => {
          console.log('result:', result)
          const info = result.data?.data?.userInfo;
          const userId = result.data?.data?.userId;
          // 根据用户信息接口返回的用户id，过滤出路由表
          commit('SET_ASYNC_ROUTES', userId)
          commit('SET_USER_INFO', info)
          commit('SET_ROLES', userId)
          resolve({msg: '获取用户信息ok', code: 0})
        })
      })
    },
    // 推出登陆按钮调用
    GetLogout({ commit }:any) {
      return new Promise((resolve, reject) => {
        commit('SET_TOEKN', '')
        resolve({msg: '推出登陆成功', code: 0})
      })
    },
  }
}

export { users  }
